<template>
  <div class="image-manage">
    <div class="page-header">
      <h1>图片管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showUploadDialog = true" :icon="Upload">上传图片</el-button>
        <el-button @click="showCategoryDialog = true" :icon="FolderAdd">新建分类</el-button>
        <el-button @click="refreshImages" :icon="Refresh">刷新</el-button>
      </div>
    </div>

    <!-- 分类标签页 -->
    <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange" class="category-tabs">
      <el-tab-pane label="全部图片" name="all">
        <div class="images-grid">
          <div v-for="(images, category) in allImages" :key="category" class="category-section">
            <h3 class="category-title">{{ getCategoryDisplayName(category) }}</h3>
            <div class="image-grid">
              <div v-for="image in images" :key="image.name" class="image-item" @click="selectImage(image)">
                <div class="image-wrapper" :class="{ selected: selectedImage?.path === image.path }">
                  <img :src="getImageUrl(image)" :alt="image.name" />
                  <div class="image-overlay">
                    <div class="image-actions">
                      <el-button size="small" type="primary" @click.stop="previewImage(image)" :icon="View">预览</el-button>
                      <el-button size="small" type="danger" @click.stop="deleteImage(image)" :icon="Delete">删除</el-button>
                    </div>
                  </div>
                </div>
                <div class="image-info">
                  <p class="image-name" :title="image.name">{{ image.name }}</p>
                  <p class="image-size">{{ formatFileSize(image.size) }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane v-for="category in categories" :key="category" :label="getCategoryDisplayName(category)" :name="category">
        <div class="category-header">
          <h3>{{ getCategoryDisplayName(category) }}</h3>
          <div class="category-actions">
            <el-button size="small" type="primary" @click="uploadToCategory(category)" :icon="Upload">上传到此分类</el-button>
            <el-button size="small" type="danger" @click="deleteCategory(category)" :icon="Delete">删除分类</el-button>
          </div>
        </div>
        
        <div class="image-grid">
          <div v-for="image in categoryImages[category] || []" :key="image.name" class="image-item" @click="selectImage(image)">
            <div class="image-wrapper" :class="{ selected: selectedImage?.path === image.path }">
              <img :src="getImageUrl(image)" :alt="image.name" />
              <div class="image-overlay">
                <div class="image-actions">
                  <el-button size="small" type="primary" @click.stop="previewImage(image)" :icon="View">预览</el-button>
                  <el-button size="small" @click.stop="renameImage(image)" :icon="Edit">重命名</el-button>
                  <el-button size="small" type="danger" @click.stop="deleteImage(image)" :icon="Delete">删除</el-button>
                </div>
              </div>
            </div>
            <div class="image-info">
              <p class="image-name" :title="image.name">{{ image.name }}</p>
              <p class="image-size">{{ formatFileSize(image.size) }}</p>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 图片选择信息 -->
    <div v-if="selectedImage" class="selected-info">
      <h4>已选择图片</h4>
      <div class="selected-details">
        <img :src="getImageUrl(selectedImage)" :alt="selectedImage.name" class="selected-preview" />
        <div class="selected-meta">
          <p><strong>文件名：</strong>{{ selectedImage.name }}</p>
          <p><strong>路径：</strong>{{ selectedImage.path }}</p>
          <p><strong>大小：</strong>{{ formatFileSize(selectedImage.size) }}</p>
          <p><strong>分类：</strong>{{ selectedImage.category ? getCategoryDisplayName(selectedImage.category) : '未知分类' }}</p>
        </div>
        <div class="selected-actions">
          <el-button type="primary" @click="copyImagePath">复制路径</el-button>
          <el-button @click="selectedImage = null">取消选择</el-button>
        </div>
      </div>
    </div>

    <!-- 上传对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传图片" width="500px">
      <el-form>
        <el-form-item label="选择分类">
          <el-select v-model="uploadCategory" placeholder="请选择图片分类">
            <el-option v-for="category in categories" :key="category" :label="getCategoryDisplayName(category)" :value="category" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择图片">
          <el-upload
            ref="uploadRef"
            :action="`${API_BASE_URL}/images/upload/${uploadCategory}`"
            :auto-upload="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept="image/*"
            multiple
          >
            <el-button type="primary" :icon="Upload">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/jpeg/png/gif/webp 格式，单个文件不超过 50MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUploadDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :disabled="!uploadCategory">开始上传</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新建分类对话框 -->
    <el-dialog v-model="showCategoryDialog" title="新建分类" width="400px">
      <el-form>
        <el-form-item label="分类名称">
          <el-input v-model="newCategoryName" placeholder="请输入分类名称（英文）" />
          <div class="form-tip">建议使用英文名称，如：attractions、food、culture 等</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCategoryDialog = false">取消</el-button>
          <el-button type="primary" @click="createCategory" :disabled="!newCategoryName.trim()">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="showPreviewDialog" :title="previewImageData?.name" width="80%" top="5vh">
      <div class="preview-container">
        <img :src="getImageUrl(previewImageData)" :alt="previewImageData?.name" class="preview-image" />
      </div>
    </el-dialog>

    <!-- 重命名对话框 -->
    <el-dialog v-model="showRenameDialog" title="重命名图片" width="400px">
      <el-form>
        <el-form-item label="新文件名">
          <el-input v-model="newImageName" placeholder="请输入新的文件名（包含扩展名）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRenameDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmRename" :disabled="!newImageName.trim()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus'
import { Upload, FolderAdd, Refresh, View, Edit, Delete } from '@element-plus/icons-vue'

const API_BASE_URL = 'http://localhost:8080/api'
const IMAGE_BASE_URL = 'http://localhost:8080/'

interface ImageInfo {
  name: string
  path: string
  category?: string
  size: number
  lastModified: number
}

const categories = ref<string[]>([])
const categoryImages = ref<Record<string, ImageInfo[]>>({})
const allImages = ref<Record<string, ImageInfo[]>>({})
const activeCategory = ref('all')
const selectedImage = ref<ImageInfo | null>(null)

// 对话框状态
const showUploadDialog = ref(false)
const showCategoryDialog = ref(false)
const showPreviewDialog = ref(false)
const showRenameDialog = ref(false)

// 表单数据
const uploadCategory = ref('')
const newCategoryName = ref('')
const newImageName = ref('')
const previewImageData = ref<ImageInfo | null>(null)
const renameImageData = ref<ImageInfo | null>(null)

const uploadRef = ref<InstanceType<typeof ElUpload>>()

// 分类显示名称映射
const categoryDisplayNames: Record<string, string> = {
  attractions: '景点图片',
  food: '美食图片',
  culture: '文化图片',
  carousel: '轮播图片'
}

const getCategoryDisplayName = (category: string) => {
  return categoryDisplayNames[category] || category
}

// 生成图片URL（使用新的文件端点处理中文文件名）
const getImageUrl = (image: ImageInfo | null) => {
  if (!image || !image.category) {
    return image ? IMAGE_BASE_URL + image.path : ''
  }
  // 使用新的文件端点，确保中文文件名能正确处理
  return `${API_BASE_URL}/images/file/${image.category}/${encodeURIComponent(image.name)}`
}

// 加载图片分类
const loadCategories = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/images/categories`)
    if (response.ok) {
      categories.value = await response.json()
      if (categories.value.length > 0 && !uploadCategory.value) {
        uploadCategory.value = categories.value[0]
      }
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
  }
}

// 加载所有图片
const loadAllImages = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/images/all`)
    if (response.ok) {
      allImages.value = await response.json()
    }
  } catch (error) {
    console.error('加载图片失败:', error)
    ElMessage.error('加载图片失败')
  }
}

// 加载指定分类的图片
const loadCategoryImages = async (category: string) => {
  try {
    const response = await fetch(`${API_BASE_URL}/images/category/${category}`)
    if (response.ok) {
      const images = await response.json()
      categoryImages.value[category] = images
    }
  } catch (error) {
    console.error(`加载分类 ${category} 图片失败:`, error)
    ElMessage.error(`加载分类 ${category} 图片失败`)
  }
}

// 刷新图片
const refreshImages = async () => {
  await loadCategories()
  await loadAllImages()
  
  // 加载当前分类的图片
  if (activeCategory.value !== 'all') {
    await loadCategoryImages(activeCategory.value)
  }
  
  ElMessage.success('图片列表已刷新')
}

// 分类切换
const handleCategoryChange = async (tab: any) => {
  const category = tab.props.name
  if (category !== 'all' && !categoryImages.value[category]) {
    await loadCategoryImages(category)
  }
}

// 选择图片
const selectImage = (image: ImageInfo) => {
  selectedImage.value = image
}

// 预览图片
const previewImage = (image: ImageInfo) => {
  previewImageData.value = image
  showPreviewDialog.value = true
}

// 重命名图片
const renameImage = (image: ImageInfo) => {
  renameImageData.value = image
  newImageName.value = image.name
  showRenameDialog.value = true
}

// 确认重命名
const confirmRename = async () => {
  if (!renameImageData.value || !newImageName.value.trim()) return
  
  try {
    const response = await fetch(
      `${API_BASE_URL}/images/${renameImageData.value.category}/${renameImageData.value.name}`,
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ newName: newImageName.value.trim() })
      }
    )
    
    if (response.ok) {
      ElMessage.success('重命名成功')
      showRenameDialog.value = false
      await refreshImages()
    } else {
      // 检查响应是否包含JSON内容
      const contentType = response.headers.get('content-type')
      if (contentType && contentType.includes('application/json')) {
        const error = await response.json()
        ElMessage.error(error.error || '重命名失败')
      } else {
        // 如果不是JSON响应，显示HTTP状态
        ElMessage.error(`重命名失败: HTTP ${response.status}`)
      }
    }
  } catch (error) {
    console.error('重命名失败:', error)
    ElMessage.error('重命名失败: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 删除图片
const deleteImage = async (image: ImageInfo) => {
  try {
    await ElMessageBox.confirm(`确定要删除图片 "${image.name}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    const response = await fetch(
      `${API_BASE_URL}/images/${image.category}/${image.name}`,
      { method: 'DELETE' }
    )
    
    if (response.ok) {
      ElMessage.success('删除成功')
      if (selectedImage.value?.path === image.path) {
        selectedImage.value = null
      }
      await refreshImages()
    } else {
      const error = await response.json()
      ElMessage.error(error.error || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传到指定分类
const uploadToCategory = (category: string) => {
  uploadCategory.value = category
  showUploadDialog.value = true
}

// 创建分类
const createCategory = async () => {
  if (!newCategoryName.value.trim()) return
  
  try {
    const response = await fetch(`${API_BASE_URL}/images/category/${newCategoryName.value.trim()}`, {
      method: 'POST'
    })
    
    if (response.ok) {
      ElMessage.success('分类创建成功')
      showCategoryDialog.value = false
      newCategoryName.value = ''
      await loadCategories()
    } else {
      const error = await response.json()
      ElMessage.error(error.error || '创建失败')
    }
  } catch (error) {
    console.error('创建分类失败:', error)
    ElMessage.error('创建分类失败')
  }
}

// 删除分类
const deleteCategory = async (category: string) => {
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${getCategoryDisplayName(category)}" 吗？只有空分类才能删除。`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    const response = await fetch(`${API_BASE_URL}/images/category/${category}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      ElMessage.success('分类删除成功')
      await loadCategories()
      if (activeCategory.value === category) {
        activeCategory.value = 'all'
      }
    } else {
      const error = await response.json()
      ElMessage.error(error.error || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  }
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt50M = file.size / 1024 / 1024 < 50
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('图片大小不能超过 50MB!')
    return false
  }
  return true
}

// 开始上传
const submitUpload = () => {
  if (!uploadCategory.value) {
    ElMessage.warning('请选择分类')
    return
  }
  uploadRef.value?.submit()
}

// 上传成功
const handleUploadSuccess = (response: any) => {
  ElMessage.success('上传成功')
  refreshImages()
}

// 上传失败
const handleUploadError = (error: any) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败')
}

// 复制图片路径
const copyImagePath = () => {
  if (!selectedImage.value) return
  
  navigator.clipboard.writeText(selectedImage.value.path).then(() => {
    ElMessage.success('路径已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

onMounted(() => {
  refreshImages()
})
</script>

<style scoped>
.image-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.category-tabs {
  margin-bottom: 20px;
}

.category-section {
  margin-bottom: 30px;
}

.category-title {
  color: #2c3e50;
  border-bottom: 2px solid #e74c3c;
  padding-bottom: 10px;
  margin-bottom: 15px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.category-actions {
  display: flex;
  gap: 10px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.image-item {
  cursor: pointer;
  transition: transform 0.3s;
}

.image-item:hover {
  transform: translateY(-5px);
}

.image-wrapper {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.image-wrapper.selected {
  border: 3px solid #e74c3c;
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
}

.image-wrapper img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  display: block;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.image-actions {
  display: flex;
  gap: 5px;
}

.image-info {
  padding: 10px;
  background: white;
}

.image-name {
  margin: 0 0 5px 0;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.image-size {
  margin: 0;
  color: #666;
  font-size: 12px;
}

.selected-info {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  width: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 20px;
  z-index: 1000;
}

.selected-info h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.selected-preview {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 15px;
}

.selected-meta p {
  margin: 5px 0;
  font-size: 14px;
}

.selected-actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.form-tip {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.preview-container {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 